//
//  HCOAuthViewController.swift
//  新浪微博
//
//  Created by fanhoucheng on 16/9/25.
//  Copyright © 2016年 fanhoucheng. All rights reserved.
//

import UIKit
import SVProgressHUD

//App Key：client_id=1615155344
//App Secret：redirect_uri=9bc87e1ebe1ff83162c8790b2ae1d06f
//https://api.weibo.com/oauth2/authorize?client_id=1615155344&redirect_uri=http://www.itheima.com
class HCOAuthViewController: UIViewController {

    lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.backgroundColor = UIColor.white
        
        webView.isOpaque = false
        //加载授权页面
        view = webView
        webView.delegate = self
        
        
        loadOAuthPage()
        setNavBar()
    }
    
    func loadOAuthPage() {
        let oauthPageString = "https://api.weibo.com/oauth2/authorize?client_id=1615155344&redirect_uri=http://www.itheima.com"
        
        let url = URL(string: oauthPageString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    
    //设置返回
    func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(backVisitorView))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "设置默认", target: self, action: #selector(setDefaultUser))
    }
    
    func backVisitorView() {
        //设置返回
        navigationController?.dismiss(animated: true, completion: { 
            
        })
    }
    
    func setDefaultUser() {
        //获取默认值
        let jsString = "document.getElementById('userId').value = '15011317280', document.getElementById('passwd').value = 'abstract757386' "
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
}

extension HCOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //每次加载页面都会调用这个方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取请求,
        let urlString = request.url?.absoluteString ?? ""
        
        let flag = "code="
        if urlString.contains(flag) {
            let query = request.url?.query ?? ""
            //获取code
            let code = (query as NSString).substring(from: flag.characters.count)
            
            //加载网络数据,通过viewModel来封装,通过闭包的方式来传递
            HCUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code: code, finished: { (state) in
                //如果成功和失败
                if !state {
                    SVProgressHUD.showError(withStatus: errorTip)
                    return
                }
                NotificationCenter.default.post(name: Notification.Name(kChnageRootViewController), object: "welcome")
            })
            //loadAccessToken(code: code)
        }
        return true
    }
    

}
